package com.ccp.dev.extend.service;

import com.ccp.dev.core.basic.engine.IScript;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringPool;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.system.consts.SecretUtil;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysOrgService;
import org.springframework.stereotype.Service;

/**
 * @author 创新中心-王明亮
 */
@Service
public class ExtendScriptImpl implements IScript {

    /**
     * 获取当前用户的密级
     * <pre>
     * 脚本中使用方法:
     * extendScriptImpl.getCurrentSecret();
     * </pre>
     *
     * @return 用户密级
     */
    public String getCurrentSecret() throws Exception {
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        if (sysUser == null) {
            return "0";
        }
        return sysUser.getPrivacyLevel().toString();
    }

    /**
     * 获取当前用户的密级对应的数据密级
     * <pre>
     * 脚本中使用方法:
     * extendScriptImpl.getCurrentDataSecret();
     * </pre>
     *
     * @return 用户密级
     */
    public String getCurrentDataSecret() throws Exception {
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        if (sysUser == null) {
            return "0";
        }
        return SecretUtil.getUserDataSecretMap().get(sysUser.getPrivacyLevel()).toString();
    }

    /**
     * 取得当前用户组织的code。
     * <pre>
     * 脚本中使用方法:
     * extendScriptImpl.getCurrentOrgCode();
     * </pre>
     *
     * @return 组织code
     */
    public String getCurrentOrgCode() {
        SysOrg sysOrg = (SysOrg) ContextUtil.getCurrentOrg();
        if (sysOrg == null) {
            return "";
        }
        return sysOrg.getCode();
    }

    /**
     * 取得当前用户的belongdeptname,获取上级是租户的组织codePath
     * <pre>
     * 脚本中使用方法:
     * extendScriptImpl.getCurrentBelongdeptname();
     * </pre>
     *
     * @return 组织code
     */
    public String getCurrentBelongdeptname() {
        SysOrg sysOrg1 = (SysOrg) ContextUtil.getCurrentOrg();
        if (sysOrg1 == null) {
            return "";
        }
        SysOrgService sysOrgService = AppUtil.getBean(SysOrgService.class);
        String code = sysOrg1.getCode();
        SysOrg sysOrg = sysOrgService.getSysOrgByOrgCode(code);
        if (StringUtil.isEmpty(code) || BeanUtils.isEmpty(sysOrg)) {
            return "";
        }
        String paths = sysOrg.getPath();
        String[] pathArr = paths.split("\\.");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 1; i < pathArr.length; i++) {
            SysOrg currOrg = sysOrgService.getOneById(pathArr[i]);
            stringBuilder.append(currOrg.getCode()).append(StringPool.DOT);
        }
        return stringBuilder.toString();
    }

}
